package com.ocm.commerceinteraction.ui;


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroupManager;
import com.easemob.luckymoneysdk.LMCallback;
import com.easemob.luckymoneysdk.core.LMMoney;
import com.google.gson.JsonSyntaxException;
import com.ocm.commerceinteraction.GlobalApplication;
import com.ocm.commerceinteraction.IndexActivity;
import com.ocm.commerceinteraction.MainActivity;
import com.ocm.commerceinteraction.R;
import com.ocm.commerceinteraction.config.RequestAddr;
import com.ocm.commerceinteraction.model.BaseModel;
import com.ocm.commerceinteraction.model.LoginModel;
import com.ocm.commerceinteraction.util.MethedUtil;
import com.ocm.commerceinteraction.util.helper.LogHelper;
import com.ocm.commerceinteraction.util.http.AjaxCallBack;
import com.ocm.commerceinteraction.util.loading.Loading;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 * 登录
 */
@EFragment(R.layout.fragment_loginin)
public class LoginInFragment extends BaseFragment {


    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;//获取编辑器

    String username;
    String password;
    int loginType = 1;//登录类型（ 1:手机号码,2:qq登录,3:微信登录,4:新浪微博）

    @ViewById(R.id.toptitle_title)
    TextView topTitle;
    @ViewById(R.id.et_useraccount)
    EditText userAccount;
    @ViewById(R.id.et_userpassword)
    EditText userPassword;

    @AfterViews
    @Override
    void initView() {
        topTitle.setText(getResources().getString(R.string.login_text));
        IndexActivity.setTranslucentStatus("#2ed5bc");
        sharedPreferences = IndexActivity.getInstance().getSharedPreferences("account_password", Context.MODE_PRIVATE); //私有数据
        editor = sharedPreferences.edit();
        username = sharedPreferences.getString("username", "");
        password = sharedPreferences.getString("password", "");
        userAccount.setText(username);
        userPassword.setText(password);
    }


    @Override
    @Click({R.id.back_btn, R.id.btn_login, R.id.tv_to_reset_pass, R.id.tv_to_register, R.id.iv_qq_login, R.id.iv_wechat_login,
            R.id.iv_weibo_login})
    void Click(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                IndexActivity.getInstance().getSupportFragmentManager().popBackStack();
                break;
            case R.id.btn_login:
                login();
                break;
            case R.id.tv_to_reset_pass:
//                IndexActivity.switchFragment(this, new ReSetPasswordFragment_());
                IndexActivity.switchFragment(this, new ResetWebFragment_());
                break;
            case R.id.tv_to_register:
                IndexActivity.switchFragment(this, new RegisterWebFragment_());
                break;
            case R.id.iv_qq_login:
//                loginQQ();
//                MethedUtil.showToast(getActivity(), "qq登录");
                loginType = 2;
                break;
            case R.id.iv_wechat_login:
//                loginWechat();
                MethedUtil.showToast(getActivity(), "微信登录");
                loginType = 3;
                break;
            case R.id.iv_weibo_login:
                loginWeibo();
                MethedUtil.showToast(getActivity(), "微博登录");
                loginType = 4;
                break;
        }
    }

    private void login() {
        username = userAccount.getText().toString().trim();
        password = userPassword.getText().toString().trim();
        if(username.equals("1")){// 快捷登陆
            username="15202373874";
            password="654321";
        }
        if (!isValidate()) {
            return;
        }
        Loading.getInstance(getActivity()).startLoading();
        param = "?user_account=" + username +
                "&password=" + password +
                "&type=" + loginType;
//        param = "?user_account=" + "zqy_qq_open_id" +
//                "&password=" + password +
//                "&type=" + "2";
//        param = "?user_account=" + "ljl_qq_open_id" +
//                "&password=" + password +
//                "&type=" + "2";
        GlobalApplication.xtHttp.get(RequestAddr.loginAddr + param, new AjaxCallBack<Object>() {
            @Override
            public void onSuccess(Object o) {
                editor.putString("username", username);
                editor.putString("password", password);
                boolean editor1 = editor.commit();
                super.onSuccess(o);
                dealResponse(o);
                DefaultHttpClient client = (DefaultHttpClient) GlobalApplication.xtHttp.getHttpClient();
                GlobalApplication.localCookie = client.getCookieStore();
                Loading.getInstance(getActivity()).stopLoading();
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                Loading.getInstance(getActivity()).stopLoading();
            }

        });
    }

    private void dealResponse(Object object) {
        try {
            GlobalApplication.loginModel = gson.fromJson(object.toString(), LoginModel.class);
        } catch (JsonSyntaxException e) {
            baseModel = gson.fromJson(object.toString(), BaseModel.class);
            MethedUtil.showToast(getActivity(), baseModel.getMsg());
            return;
        }
        doInBackground();
    }

    /**
     * 判断输入是否为空
     *
     * @return 验证是否成功
     */
    private boolean isValidate() {
        if (username.equals("") || password.equals("")) {
            MethedUtil.showToast(getActivity(), "请输入完整");
            return false;
        }
        return true;
    }


    void doInBackground() {
//
        huanxinLogin();
        Intent intent = new Intent();
        intent.setClass(IndexActivity.getInstance(), MainActivity.class);
        startActivity(intent);
        IndexActivity.getInstance().finish();
    }



    void huanxinLogin() {
        final String currentUsername = GlobalApplication.loginModel.getData().getUser_uniq_id();
        EMChatManager.getInstance().login(
                GlobalApplication.loginModel.getData().getUser_uniq_id(),
                "123456", new EMCallBack() {//回调
                    @Override
                    public void onSuccess() {
                        LogHelper.d("登陆聊天服务器成功**！");
                        EMGroupManager.getInstance().loadAllGroups();
                        EMChatManager.getInstance().loadAllConversations();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                EMGroupManager.getInstance().loadAllGroups();
                                EMChatManager.getInstance().loadAllConversations();
                                LogHelper.d("登陆聊天服务器成功！");
                            }
                        });
                        LMMoney.getInstance().initLMToken(currentUsername, currentUsername, EMChatManager.getInstance().getAccessToken(), new LMCallback() {
                            @Override
                            public void onSuccess() {
                                Log.e("redpacket", "onSuccess: " );
                            }

                            @Override
                            public void onError(String s, String s1) {
                                Log.e("redpacket", "onError: " );
                            }
                        });
                    }

                    @Override
                    public void onProgress(int progress, String status) {

                    }

                    @Override
                    public void onError(int code, String message) {
                        LogHelper.d("登陆聊天服务器失败！code" + code + ",message:" + message);
                    }
                });

    }

//    UMShareAPI mShareAPI;
//    SHARE_MEDIA platform;
//    private void loginQQ() {
//        mShareAPI = UMShareAPI.get(getActivity());
//        SHARE_MEDIA platform = SHARE_MEDIA.QQ;
//        mShareAPI.doOauthVerify(getActivity(), platform, umAuthListener);
//    }
//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        mShareAPI.onActivityResult(requestCode, resultCode, data);
//    }
//    private void loginWechat() {
//        mShareAPI = UMShareAPI.get(getActivity());
//        SHARE_MEDIA platform = SHARE_MEDIA.WEIXIN;
//        mShareAPI.doOauthVerify(getActivity(), platform, umAuthListener);
//    }

    private void loginWeibo() {

    }
//    private UMAuthListener umAuthListener = new UMAuthListener() {
//        @Override
//        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
//            Toast.makeText(getActivity(), "Authorize succeed", Toast.LENGTH_SHORT).show();
//            mShareAPI.getPlatformInfo(getActivity(), platform, umAuthListener);
//        }
//
//        @Override
//        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
//            Toast.makeText( getActivity(), "Authorize fail", Toast.LENGTH_SHORT).show();
//        }
//
//        @Override
//        public void onCancel(SHARE_MEDIA platform, int action) {
//            Toast.makeText( getActivity(), "Authorize cancel", Toast.LENGTH_SHORT).show();
//        }
//    };

    /**
     * 跳过不登录
     */
    private void jumpOutLogin() {
        Intent intent = new Intent();
        intent.setClass(IndexActivity.getInstance(), MainActivity.class);
        startActivity(intent);
        IndexActivity.getInstance().finish();
    }

}

